package top.anonyeast.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import top.anonyeast.pojo.Human;

import javax.annotation.Resource;

@RestController
public class YamlController {
    //Spring启动时会自动加载application.yaml
    @Value("${name}")
    private String name;//根据键获取值
    @Value("${person.age}")
    private Integer age;//获取对象属性
    @Value("${address[0]}")
    private String address;//获取数组元素
    @Value("${msg1}")
    private String message1;
    @Value("${msg2}")
    private String message2;

    //以上方式虽然可以获取到配置文件中注入的内容，但十分麻烦
    //使用Environment对象获取值会比较方便
    @Autowired
    private Environment env;
    @Resource(name = "human")
    private Human human;
    @RequestMapping("/hello")
    public String hello(){
        System.out.println("使用@Value注解获取属性值：");
        System.out.println("name = " + name);
        System.out.println("age = " + age);
        System.out.println("address = " + address);
        System.out.println("message1 = " + message1);//原样输出
        System.out.println("message2 = " + message2);//转义
        System.out.println("---------------------");
        System.out.println("使用Environment对象获取属性值：");
        System.out.println(env.getProperty("person.name"));
        System.out.println(env.getProperty("address[0]"));
        System.out.println("---------------------");
        System.out.println("使用@ConfigurationProperties注解直接封装对象：");
        System.out.println("human = " + human);
        String[] address = human.getAddress();
        return "Hello Spring Boot";
    }
}
